package com.example.luckin.slice.provider;

import com.example.luckin.ResourceTable;
import com.example.luckin.slice.entity.MainItem;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.IOException;
import java.util.List;

public class MainItemProvider extends BaseItemProvider {

    private List<MainItem> items;
    private Context context;

    public MainItemProvider() {
    }

    public MainItemProvider(Context context, List<MainItem> items) {
        this.items = items;
        this.context = context;
    }

    @Override
    public int getCount() {
        System.out.println("getCount = " + items.size());
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        System.out.println("getItem = " + i);
        return null;
    }

    @Override
    public long getItemId(int i) {
        System.out.println("GetItemId = " + i);
        return 0;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        if (component == null) {
            component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_fraction_main_item, componentContainer, false);
            MainItemHolder mainItemHolder = new MainItemHolder();
            mainItemHolder.button = (Button) component.findComponentById(ResourceTable.Id_btn_item);
            mainItemHolder.title = (Text) component.findComponentById(ResourceTable.Id_txt_title);
            mainItemHolder.desc = (Text) component.findComponentById(ResourceTable.Id_txt_desc);
            component.setTag(mainItemHolder);
        }
        MainItemHolder mainItemHolder = (MainItemHolder) component.getTag();
        MainItem mainItem = items.get(i);
        try {
            Resource resource = context.getResourceManager().getResource(mainItem.getImg());
            PixelMapElement element = new PixelMapElement(resource);
            mainItemHolder.button.setBackground(element);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        mainItemHolder.title.setText(mainItem.getTitle());
        mainItemHolder.desc.setText(mainItem.getDesc());
        return component;
    }

    // 创建Holder类，用于列表优化
    public class MainItemHolder {
        private Button button;
        private Text title;
        private Text desc;
    }
}
